import React, { useState, useEffect, useRef } from 'react'
import { Plus, Edit2, Save, X, Trash2, Download, Upload } from 'lucide-react'
import * as XLSX from 'xlsx'
import { weeklyTodoAPI, personnelAPI } from '../services/api'

const WeeklyMeetingTodos = () => {
  // 人员信息状态
  const [personnel, setPersonnel] = useState([])
  
  // 待办事项数据状态
  const [todos, setTodos] = useState([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(null)

  // 编辑状态
  const [editingCell, setEditingCell] = useState(null)
  const [editValue, setEditValue] = useState('')
  const [showAddForm, setShowAddForm] = useState(false)
  const [editingTodo, setEditingTodo] = useState(null)
  const [hideCompleted, setHideCompleted] = useState(false)
  const fileInputRef = useRef(null)
  const [formData, setFormData] = useState({
    responsiblePerson: '',
    task: '',
    plannedCompletionTime: '',
    delayedCompletionTime: '',
    closure: '非闭环',
    remarks: ''
  })

  // 从API加载数据
  useEffect(() => {
    loadData()
  }, [])

  // 加载待办事项和人员数据
  const loadTodos = async () => {
    try {
      setLoading(true)
      setError(null)
      const response = await weeklyTodoAPI.getAll()
      const backendTodos = response.results || response
      const frontendTodos = backendTodos.map(mapToFrontend)
      setTodos(frontendTodos)
    } catch (err) {
      setError('加载待办事项失败: ' + err.message)
      console.error('Failed to load todos:', err)
    } finally {
      setLoading(false)
    }
  }

  // 加载人员数据
  const loadPersonnel = async () => {
    try {
      const response = await personnelAPI.getAll()
      setPersonnel(response.results || response)
    } catch (err) {
      console.error('Failed to load personnel:', err)
      // 人员数据加载失败不影响主要功能
    }
  }

  // 加载所有数据
  const loadData = async () => {
    await Promise.all([loadTodos(), loadPersonnel()])
  }

  // 字段映射：前端驼峰命名 -> 后端下划线命名
  const mapToBackend = (frontendData) => {
    return {
      responsible_person: frontendData.responsiblePerson,
      task: frontendData.task,
      planned_completion_time: frontendData.plannedCompletionTime,
      delayed_completion_time: frontendData.delayedCompletionTime,
      closure: frontendData.closure,
      remarks: frontendData.remarks
    }
  }

  // 字段映射：后端下划线命名 -> 前端驼峰命名
  const mapToFrontend = (backendData) => {
    return {
      id: backendData.id,
      responsiblePerson: backendData.responsible_person,
      task: backendData.task,
      plannedCompletionTime: backendData.planned_completion_time,
      delayedCompletionTime: backendData.delayed_completion_time,
      closure: backendData.closure,
      remarks: backendData.remarks,
      createdAt: backendData.created_at,
      updatedAt: backendData.updated_at
    }
  }

  // 开始编辑
  const startEdit = (id, field) => {
    const todo = todos.find(t => t.id === id)
    const value = todo ? todo[field] : ''
    setEditingCell(`${id}-${field}`)
    setEditValue(value || '')
  }

  // 保存编辑
  const saveEdit = async () => {
    if (!editingCell) return
    
    const [id, field] = editingCell.split('-')
    const todoId = parseInt(id)
    
    try {
      // 将前端字段名映射为后端字段名
      const fieldMapping = {
        responsiblePerson: 'responsible_person',
        plannedCompletionTime: 'planned_completion_time',
        delayedCompletionTime: 'delayed_completion_time'
      }
      const backendField = fieldMapping[field] || field
      
      // 调用API更新数据
      const updatedTodo = await weeklyTodoAPI.patch(todoId, { [backendField]: editValue })
      
      // 更新本地状态
      setTodos(prev => prev.map(todo => 
        todo.id === todoId 
          ? mapToFrontend(updatedTodo)
          : todo
      ))
      
      setEditingCell(null)
      setEditValue('')
    } catch (err) {
      alert('保存失败: ' + err.message)
      console.error('Failed to save edit:', err)
    }
  }

  // 取消编辑
  const cancelEdit = () => {
    setEditingCell(null)
    setEditValue('')
  }

  // 添加或修改事项
  const handleSubmit = async (e) => {
    e.preventDefault()
    
    // 验证必填字段
    if (!formData.task.trim()) {
      alert('请填写事项内容')
      return
    }
    
    if (!formData.responsiblePerson.trim()) {
      alert('请选择至少一个责任人')
      return
    }
    
    try {
       if (editingTodo) {
         // 修改现有事项
         const backendData = mapToBackend(formData)
         const updatedTodo = await weeklyTodoAPI.update(editingTodo, backendData)
         
         setTodos(prev => prev.map(todo => 
           todo.id === editingTodo 
             ? mapToFrontend(updatedTodo)
             : todo
         ))
       } else {
         // 添加新事项
         const backendData = mapToBackend(formData)
         const newTodo = await weeklyTodoAPI.create(backendData)
         
         setTodos(prev => [...prev, mapToFrontend(newTodo)])
       }
     } catch (err) {
       alert('保存失败: ' + err.message)
       console.error('Failed to save todo:', err)
       return
     }
    
    // 重置表单
    setFormData({
      responsiblePerson: '',
      task: '',
      plannedCompletionTime: '',
      delayedCompletionTime: '',
      closure: '非闭环',
      remarks: ''
    })
    setEditingTodo(null)
    setShowAddForm(false)
  }

  // 开始修改事项
  const startEditTodo = (todo) => {
    setEditingTodo(todo.id)
    setFormData({
      responsiblePerson: todo.responsiblePerson || '',
      task: todo.task || '',
      plannedCompletionTime: todo.plannedCompletionTime || '',
      delayedCompletionTime: todo.delayedCompletionTime || '',
      closure: todo.closure || '非闭环',
      remarks: todo.remarks || ''
    })
    setShowAddForm(true)
  }

  // 删除事项
  const deleteTodo = async (id) => {
    if (window.confirm('确定要删除这个事项吗？')) {
      try {
        await weeklyTodoAPI.delete(id)
        // 重新加载数据以确保前后端状态一致
        await loadTodos()
      } catch (err) {
        alert('删除失败: ' + err.message)
        console.error('Failed to delete todo:', err)
      }
    }
  }

  // 导出Excel
  const exportToExcel = () => {
    if (todos.length === 0) {
      alert('暂无数据可导出')
      return
    }

    // 准备导出数据
    const exportData = todos.map((todo, index) => ({
      '序号': index + 1,
      '责任人': todo.responsiblePerson || '',
      '事项': todo.task || '',
      '计划完成时间': todo.plannedCompletionTime || '',
      '推迟完成时间': todo.delayedCompletionTime || '',
      '闭环': todo.closure || '',
      '备注': todo.remarks || ''
    }))

    // 创建CSV内容
    const headers = ['序号', '责任人', '事项', '计划完成时间', '推迟完成时间', '闭环', '备注']
    const csvContent = [
      headers.join(','),
      ...exportData.map(row => 
        headers.map(header => {
          const value = row[header] || ''
          // 处理包含逗号或换行的字段
          return value.toString().includes(',') || value.toString().includes('\n') 
            ? `"${value.toString().replace(/"/g, '""')}"` 
            : value
        }).join(',')
      )
    ].join('\n')

    // 添加BOM以支持中文
    const BOM = '\uFEFF'
    const blob = new Blob([BOM + csvContent], { type: 'text/csv;charset=utf-8;' })
    
    // 创建下载链接
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    link.setAttribute('href', url)
    
    // 生成文件名
    const now = new Date()
    const dateStr = now.getFullYear() + 
      String(now.getMonth() + 1).padStart(2, '0') + 
      String(now.getDate()).padStart(2, '0')
    link.setAttribute('download', `周会待办事项统计_${dateStr}.csv`)
    
    // 触发下载
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)
  }

  // 处理文件上传
  const handleFileUpload = (e) => {
    const file = e.target.files[0]
    if (!file) return

    const reader = new FileReader()
    reader.onload = async (event) => {
      try {
        const data = new Uint8Array(event.target.result)
        const workbook = XLSX.read(data, { type: 'array' })
        const sheetName = workbook.SheetNames[0]
        const worksheet = workbook.Sheets[sheetName]
        const json = XLSX.utils.sheet_to_json(worksheet)

        if (json.length === 0) {
          alert('Excel文件为空或格式不正确')
          return
        }

        // 验证表头（只有责任人和事项为必需列，其他列为可选）
        const requiredHeaders = ['责任人', '事项']
        const actualHeaders = Object.keys(json[0])
        const missingHeaders = requiredHeaders.filter(h => !actualHeaders.includes(h))

        if (missingHeaders.length > 0) {
          alert(`导入失败，Excel文件缺少以下必需列：${missingHeaders.join(', ')}`)
          return
        }

        // 转换数据为后端格式
        const newTodos = json.map((row) => ({
          responsible_person: row['责任人'] || '',
          task: row['事项'] || '',
          planned_completion_time: excelDateToJSDate(row['计划完成时间']) || '',
          delayed_completion_time: excelDateToJSDate(row['推迟完成时间']) || '',
          closure: row['闭环'] || '非闭环',
          remarks: row['备注'] || ''
        }))

        // 批量保存到数据库
        try {
          const response = await weeklyTodoAPI.bulkCreate(newTodos)
          // 重新加载数据以获取最新的ID和时间戳
          await loadTodos()
          alert(`数据导入成功！共导入 ${response.length} 条记录。`)
        } catch (saveError) {
          console.error('保存到数据库失败:', saveError)
          alert('导入失败：保存到数据库时出错。请检查数据格式是否正确。')
        }

      } catch (error) {
        console.error('导入Excel时出错:', error)
        alert('导入失败，请确保文件是有效的Excel格式。')
      }
    }
    reader.readAsArrayBuffer(file)

    // 重置input，以便可以再次选择同一个文件
    e.target.value = null
  }

  // 触发文件选择
  const triggerFileUpload = () => {
    fileInputRef.current.click()
  }

  // Excel序列号转日期
  const excelDateToJSDate = (serial) => {
    if (typeof serial !== 'number' || isNaN(serial)) {
      return serial; // 如果不是数字或已经是日期字符串，直接返回
    }
    const utc_days = Math.floor(serial - 25569);
    const utc_value = utc_days * 86400;
    const date_info = new Date(utc_value * 1000);

    const fractional_day = serial - Math.floor(serial) + 0.0000001;

    let total_seconds = Math.floor(86400 * fractional_day);

    const seconds = total_seconds % 60;

    total_seconds -= seconds;

    const hours = Math.floor(total_seconds / (60 * 60));
    const minutes = Math.floor(total_seconds / 60) % 60;

    const date = new Date(date_info.getFullYear(), date_info.getMonth(), date_info.getDate(), hours, minutes, seconds);
    
    // 格式化为 YYYY-MM-DD
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');

    return `${year}-${month}-${day}`;
  }

     // 渲染编辑单元格
  const renderEditableCell = (id, field, value, isSelect = false, selectOptions = []) => {
    const cellKey = `${id}-${field}`
    const isEditing = editingCell === cellKey
    
    if (isEditing) {
      if (isSelect && field === 'responsiblePerson') {
        // 责任人多选编辑
        return (
          <div style={{ display: 'flex', flexDirection: 'column', gap: '4px', minWidth: '200px' }}>
            <div style={{
              minHeight: '32px',
              padding: '4px',
              border: '1px solid #d9d9d9',
              borderRadius: '4px',
              background: 'white',
              display: 'flex',
              flexWrap: 'wrap',
              gap: '4px',
              alignItems: 'center'
            }}>
              {editValue.split(',').filter(name => name.trim()).map((name, index) => (
                <span
                  key={index}
                  style={{
                    background: '#e3f2fd',
                    color: '#1976d2',
                    padding: '3px 8px',
                    borderRadius: '12px',
                    fontSize: '14px',
                    display: 'flex',
                    alignItems: 'center',
                    gap: '2px'
                  }}
                >
                  {name.trim()}
                  <button
                    type="button"
                    onClick={() => {
                      const names = editValue.split(',').filter(n => n.trim() !== name.trim())
                      setEditValue(names.join(','))
                    }}
                    style={{
                      background: 'none',
                      border: 'none',
                      color: '#1976d2',
                      cursor: 'pointer',
                      fontSize: '12px',
                      padding: '0',
                      width: '14px',
                      height: '14px',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center'
                    }}
                  >
                    ×
                  </button>
                </span>
              ))}
              <select
                value=""
                onChange={(e) => {
                  if (e.target.value) {
                    const currentNames = editValue ? editValue.split(',').map(n => n.trim()).filter(n => n) : []
                    if (!currentNames.includes(e.target.value)) {
                      const newNames = [...currentNames, e.target.value]
                      setEditValue(newNames.join(','))
                    }
                  }
                }}
                style={{
                  border: 'none',
                  background: 'transparent',
                  outline: 'none',
                  flex: 1,
                  minWidth: '80px',
                  fontSize: '11px'
                }}
              >
                <option value="">+ 选择</option>
                {selectOptions.filter(option => 
                  !editValue.split(',').map(n => n.trim()).includes(option.value)
                ).map(option => (
                  <option key={option.value} value={option.value}>{option.label}</option>
                ))}
              </select>
            </div>
            <div style={{ display: 'flex', gap: '4px', justifyContent: 'flex-end' }}>
              <button 
                onClick={saveEdit} 
                title="保存"
                style={{ 
                  padding: '4px', 
                  fontSize: '12px', 
                  background: '#27ae60', 
                  color: 'white', 
                  border: 'none', 
                  borderRadius: '3px'
                }}
              >
                ✓
              </button>
              <button 
                onClick={cancelEdit} 
                title="取消"
                style={{ 
                  padding: '4px', 
                  fontSize: '12px', 
                  background: '#e74c3c', 
                  color: 'white', 
                  border: 'none', 
                  borderRadius: '3px'
                }}
              >
                ✕
              </button>
            </div>
          </div>
        )
      } else if (isSelect) {
        // 其他下拉选择（如闭环状态）
        return (
          <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
            <select
              value={editValue}
              onChange={(e) => setEditValue(e.target.value)}
              style={{ 
                flex: 1, 
                padding: '4px', 
                border: '1px solid #d9d9d9', 
                borderRadius: '4px',
                fontSize: '12px'
              }}
            >
              {selectOptions.map(option => (
                <option key={option.value} value={option.value}>{option.label}</option>
              ))}
            </select>
            <button 
              onClick={saveEdit} 
              title="保存"
              style={{ 
                padding: '4px', 
                fontSize: '12px', 
                background: '#27ae60', 
                color: 'white', 
                border: 'none', 
                borderRadius: '3px'
              }}
            >
              ✓
            </button>
            <button 
              onClick={cancelEdit} 
              title="取消"
              style={{ 
                padding: '4px', 
                fontSize: '12px', 
                background: '#e74c3c', 
                color: 'white', 
                border: 'none', 
                borderRadius: '3px'
              }}
            >
              ✕
            </button>
          </div>
        )
      } else {
        return (
          <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
            <input
              type={field.includes('Time') ? 'date' : 'text'}
              value={editValue}
              onChange={(e) => setEditValue(e.target.value)}
              style={{ 
                flex: 1, 
                padding: '4px', 
                border: '1px solid #d9d9d9', 
                borderRadius: '4px',
                fontSize: '12px'
              }}
            />
            <button 
              onClick={saveEdit} 
              title="保存"
              style={{ 
                padding: '4px', 
                fontSize: '12px', 
                background: '#27ae60', 
                color: 'white', 
                border: 'none', 
                borderRadius: '3px'
              }}
            >
              ✓
            </button>
            <button 
              onClick={cancelEdit} 
              title="取消"
              style={{ 
                padding: '4px', 
                fontSize: '12px', 
                background: '#e74c3c', 
                color: 'white', 
                border: 'none', 
                borderRadius: '3px'
              }}
            >
              ✕
            </button>
          </div>
        )
      }
    }
    
    return (
      <div 
        onClick={() => startEdit(id, field)}
        style={{ 
          cursor: 'pointer', 
          minHeight: '20px', 
          padding: '4px',
          border: '1px solid transparent',
          borderRadius: '4px',
          color: value ? '#333' : '#999'
        }}
        title="点击编辑"
      >
        {field === 'responsiblePerson' && value ? (
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: '4px' }}>
            {value.split(',').filter(name => name.trim()).map((name, index) => (
              <span
                key={index}
                style={{
                  background: '#e8f5e8',
                  color: '#2e7d2e',
                  padding: '3px 8px',
                  borderRadius: '12px',
                  fontSize: '14px'
                }}
              >
                {name.trim()}
              </span>
            ))}
          </div>
        ) : (
          value || '点击编辑'
        )}
      </div>
    )
  }

  const personnelOptions = personnel.map(p => ({ value: p.name, label: p.name }))
  const closureOptions = [
    { value: '非闭环', label: '非闭环' },
    { value: '已闭环', label: '已闭环' }
  ]

  // 加载状态显示
  if (loading) {
    return (
      <div className="card">
        <div style={{ textAlign: 'center', padding: '40px' }}>
          <p>正在加载待办事项数据...</p>
        </div>
      </div>
    )
  }

  // 错误状态显示
  if (error) {
    return (
      <div className="card">
        <div style={{ textAlign: 'center', padding: '40px' }}>
          <p style={{ color: 'red', marginBottom: '16px' }}>{error}</p>
          <button className="btn btn-primary" onClick={loadData}>
            重新加载
          </button>
        </div>
      </div>
    )
  }

  return (
    <div className="card">
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px' }}>
          <h2 style={{ fontSize: '24px', fontWeight: 'bold', margin: 0 }}>周会待办事项统计</h2>
          <div style={{ display: 'flex', alignItems: 'center', gap: '20px' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
              <label htmlFor="hideCompleted" style={{ fontSize: '14px', color: '#666' }}>隐藏已闭环内容</label>
              <input
                type="checkbox"
                id="hideCompleted"
                checked={hideCompleted}
                onChange={(e) => setHideCompleted(e.target.checked)}
                style={{
                  width: '16px',
                  height: '16px',
                  accentColor: '#10b981'
                }}
              />
            </div>
            <div style={{ display: 'flex', gap: '12px' }}>
              <button 
                onClick={() => {
                  setEditingTodo(null)
                  setFormData({
                    responsiblePerson: '',
                    task: '',
                    plannedCompletionTime: '',
                    delayedCompletionTime: '',
                    closure: '非闭环',
                    remarks: ''
                  })
                  setShowAddForm(true)
                }}
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: '6px',
                  padding: '8px 16px',
                  background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                  color: 'white',
                  border: 'none',
                  borderRadius: '8px',
                  fontSize: '14px',
                  fontWeight: '500',
                  cursor: 'pointer',
                  transition: 'all 0.2s ease',
                  boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
                }}
                onMouseEnter={(e) => {
                  e.target.style.transform = 'translateY(-1px)'
                  e.target.style.boxShadow = '0 4px 8px rgba(0,0,0,0.15)'
                }}
                onMouseLeave={(e) => {
                  e.target.style.transform = 'translateY(0)'
                  e.target.style.boxShadow = '0 2px 4px rgba(0,0,0,0.1)'
                }}
              >
                <Plus size={16} />
                新增事项
              </button>
              <input 
                type="file" 
                ref={fileInputRef} 
                onChange={handleFileUpload}
                style={{ display: 'none' }}
                accept=".xlsx, .xls, .csv"
              />
              <button 
                onClick={() => fileInputRef.current.click()}
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: '6px',
                  padding: '8px 16px',
                  background: 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)',
                  color: 'white',
                  border: 'none',
                  borderRadius: '8px',
                  fontSize: '14px',
                  fontWeight: '500',
                  cursor: 'pointer',
                  transition: 'all 0.2s ease',
                  boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
                }}
                onMouseEnter={(e) => {
                  e.target.style.transform = 'translateY(-1px)'
                  e.target.style.boxShadow = '0 4px 8px rgba(0,0,0,0.15)'
                }}
                onMouseLeave={(e) => {
                  e.target.style.transform = 'translateY(0)'
                  e.target.style.boxShadow = '0 2px 4px rgba(0,0,0,0.1)'
                }}
              >
                <Upload size={16} />
                导入Excel
              </button>
              <button 
                onClick={exportToExcel}
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: '6px',
                  padding: '8px 16px',
                  background: 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)',
                  color: 'white',
                  border: 'none',
                  borderRadius: '8px',
                  fontSize: '14px',
                  fontWeight: '500',
                  cursor: 'pointer',
                  transition: 'all 0.2s ease',
                  boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
                }}
                onMouseEnter={(e) => {
                  e.target.style.transform = 'translateY(-1px)'
                  e.target.style.boxShadow = '0 4px 8px rgba(0,0,0,0.15)'
                }}
                onMouseLeave={(e) => {
                  e.target.style.transform = 'translateY(0)'
                  e.target.style.boxShadow = '0 2px 4px rgba(0,0,0,0.1)'
                }}
              >
                <Download size={16} />
                导出Excel
              </button>
            </div>
          </div>
        </div>

      {/* 新增事项表单 */}
      {showAddForm && (
        <div style={{ 
          background: '#f8f9fa', 
          padding: '20px', 
          borderRadius: '8px', 
          marginBottom: '20px',
          border: '1px solid #e9ecef'
        }}>
          <h3 style={{ marginBottom: '16px' }}>
            {editingTodo ? '修改待办事项' : '新增待办事项'}
          </h3>
          <form onSubmit={handleSubmit} style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '16px' }}>
                         <div>
               <label style={{ display: 'block', marginBottom: '4px', fontWeight: '500' }}>责任人</label>
               <div style={{ position: 'relative' }}>
                 <div style={{
                   minHeight: '36px',
                   padding: '4px',
                   border: '1px solid #d9d9d9',
                   borderRadius: '4px',
                   background: 'white',
                   display: 'flex',
                   flexWrap: 'wrap',
                   gap: '4px',
                   alignItems: 'center'
                 }}>
                   {formData.responsiblePerson.split(',').filter(name => name.trim()).map((name, index) => (
                     <span
                       key={index}
                       style={{
                         background: '#e3f2fd',
                         color: '#1976d2',
                         padding: '2px 8px',
                         borderRadius: '12px',
                         fontSize: '12px',
                         display: 'flex',
                         alignItems: 'center',
                         gap: '4px'
                       }}
                     >
                       {name.trim()}
                       <button
                         type="button"
                         onClick={() => {
                           const names = formData.responsiblePerson.split(',').filter(n => n.trim() !== name.trim())
                           setFormData(prev => ({ ...prev, responsiblePerson: names.join(',') }))
                         }}
                         style={{
                           background: 'none',
                           border: 'none',
                           color: '#1976d2',
                           cursor: 'pointer',
                           fontSize: '14px',
                           padding: '0',
                           width: '16px',
                           height: '16px',
                           display: 'flex',
                           alignItems: 'center',
                           justifyContent: 'center'
                         }}
                       >
                         ×
                       </button>
                     </span>
                   ))}
                   <select
                     value=""
                     onChange={(e) => {
                       if (e.target.value) {
                         const currentNames = formData.responsiblePerson ? formData.responsiblePerson.split(',').map(n => n.trim()).filter(n => n) : []
                         if (!currentNames.includes(e.target.value)) {
                           const newNames = [...currentNames, e.target.value]
                           setFormData(prev => ({ ...prev, responsiblePerson: newNames.join(',') }))
                         }
                       }
                     }}
                     style={{
                       border: 'none',
                       background: 'transparent',
                       outline: 'none',
                       flex: 1,
                       minWidth: '120px',
                       padding: '4px'
                     }}
                   >
                     <option value="">+ 选择责任人</option>
                     {personnelOptions.filter(option => 
                       !formData.responsiblePerson.split(',').map(n => n.trim()).includes(option.value)
                     ).map(option => (
                       <option key={option.value} value={option.value}>{option.label}</option>
                     ))}
                   </select>
                 </div>
               </div>
             </div>
            
                           <div>
              <label style={{ display: 'block', marginBottom: '4px', fontWeight: '500' }}>事项</label>
              <input
                type="text"
                value={formData.task}
                onChange={(e) => setFormData(prev => ({ ...prev, task: e.target.value }))}
                style={{ width: '100%', padding: '8px', border: '1px solid #d9d9d9', borderRadius: '4px' }}
                placeholder="请输入事项内容"
              />
            </div>
            
            <div>
              <label style={{ display: 'block', marginBottom: '4px', fontWeight: '500' }}>计划完成时间</label>
              <input
                type="date"
                value={formData.plannedCompletionTime}
                onChange={(e) => setFormData(prev => ({ ...prev, plannedCompletionTime: e.target.value }))}
                style={{ width: '100%', padding: '8px', border: '1px solid #d9d9d9', borderRadius: '4px' }}
              />
            </div>
            
            <div>
              <label style={{ display: 'block', marginBottom: '4px', fontWeight: '500' }}>推迟完成时间</label>
              <input
                type="date"
                value={formData.delayedCompletionTime}
                onChange={(e) => setFormData(prev => ({ ...prev, delayedCompletionTime: e.target.value }))}
                style={{ width: '100%', padding: '8px', border: '1px solid #d9d9d9', borderRadius: '4px' }}
              />
            </div>
            
            <div>
              <label style={{ display: 'block', marginBottom: '4px', fontWeight: '500' }}>闭环</label>
              <select
                value={formData.closure}
                onChange={(e) => setFormData(prev => ({ ...prev, closure: e.target.value }))}
                style={{ width: '100%', padding: '8px', border: '1px solid #d9d9d9', borderRadius: '4px' }}
              >
                {closureOptions.map(option => (
                  <option key={option.value} value={option.value}>{option.label}</option>
                ))}
              </select>
            </div>
            
            <div>
              <label style={{ display: 'block', marginBottom: '4px', fontWeight: '500' }}>备注</label>
              <input
                type="text"
                value={formData.remarks}
                onChange={(e) => setFormData(prev => ({ ...prev, remarks: e.target.value }))}
                style={{ width: '100%', padding: '8px', border: '1px solid #d9d9d9', borderRadius: '4px' }}
              />
            </div>
            
            <div style={{ gridColumn: 'span 2', display: 'flex', gap: '8px', justifyContent: 'flex-end' }}>
              <button 
                type="button" 
                onClick={() => {
                  setShowAddForm(false)
                  setEditingTodo(null)
                  setFormData({
                    responsiblePerson: '',
                    task: '',
                    plannedCompletionTime: '',
                    delayedCompletionTime: '',
                    closure: '非闭环',
                    remarks: ''
                  })
                }}
                style={{ 
                  padding: '8px 16px', 
                  border: '1px solid #d9d9d9', 
                  background: 'white', 
                  borderRadius: '4px',
                  cursor: 'pointer'
                }}
              >
                取消
              </button>
              <button 
                type="submit"
                style={{ 
                  padding: '8px 16px', 
                  border: 'none', 
                  background: '#3498db', 
                  color: 'white',
                  borderRadius: '4px',
                  cursor: 'pointer'
                }}
              >
                {editingTodo ? '更新' : '保存'}
              </button>
            </div>
          </form>
        </div>
      )}

      {/* 待办事项表格 */}
      <table className="table">
        <thead>
          <tr>
            <th>序号</th>
            <th>责任人</th>
            <th>事项</th>
            <th>计划完成时间</th>
            <th>推迟完成时间</th>
            <th>闭环</th>
            <th>备注</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          {todos.filter(todo => !hideCompleted || (todo.closure && todo.closure.replace(/\s/g, '') !== '已闭环')).map((todo, index) => (
            <tr key={todo.id}>
              <td style={{ fontWeight: '500' }}>{index + 1}</td>
              <td>
                {renderEditableCell(
                  todo.id, 
                  'responsiblePerson', 
                  todo.responsiblePerson, 
                  true, 
                  personnelOptions
                )}
              </td>
              <td>
                {renderEditableCell(todo.id, 'task', todo.task)}
              </td>
              <td>
                {renderEditableCell(todo.id, 'plannedCompletionTime', todo.plannedCompletionTime)}
              </td>
              <td>
                {renderEditableCell(todo.id, 'delayedCompletionTime', todo.delayedCompletionTime)}
              </td>
              <td>
                {renderEditableCell(
                  todo.id, 
                  'closure', 
                  todo.closure, 
                  true, 
                  closureOptions
                )}
              </td>
              <td>
                {renderEditableCell(todo.id, 'remarks', todo.remarks)}
              </td>
              <td>
                <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
                  <button 
                    onClick={() => startEditTodo(todo)}
                    style={{ 
                      border: 'none', 
                      background: 'none', 
                      cursor: 'pointer', 
                      color: '#3498db',
                      fontSize: '16px'
                    }}
                    title="修改"
                  >
                    <Edit2 size={16} />
                  </button>
                  <button 
                    onClick={() => deleteTodo(todo.id)}
                    style={{ 
                      border: 'none', 
                      background: 'none', 
                      cursor: 'pointer', 
                      color: '#e74c3c',
                      fontSize: '16px'
                    }}
                    title="删除"
                  >
                    <Trash2 size={16} />
                  </button>
                </div>
              </td>
            </tr>
          ))}
        </tbody>
      </table>

      {todos.length === 0 && (
        <div style={{ textAlign: 'center', padding: '40px', color: '#999' }}>
          暂无待办事项，请点击"新增事项"添加
        </div>
      )}

      {personnel.length === 0 && (
        <div style={{ 
          marginTop: '20px', 
          padding: '16px', 
          background: '#fff3cd', 
          border: '1px solid #ffeaa7', 
          borderRadius: '4px',
          color: '#856404'
        }}>
          <strong>提示：</strong>请先在"信息维护"中添加人员信息，以便在此处选择责任人。
        </div>
      )}
    </div>
  )
}

export default WeeklyMeetingTodos